package com.rainkaze.lifeharbor.fragment;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.databinding.FragmentItemRandomBinding;
import com.rainkaze.lifeharbor.model.ToolItem;
import com.rainkaze.lifeharbor.utils.ToolRepository;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomItemFragment extends Fragment implements SensorEventListener {

    private FragmentItemRandomBinding binding;
    private SensorManager sensorManager;
    private Sensor accelerometer;

    private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F;
    private static final int SHAKE_SLOP_TIME_MS = 500;
    private static final int SHAKE_COUNT_RESET_TIME_MS = 3000;

    private long lastShakeTimestamp;
    private float lastX, lastY, lastZ;
    private boolean isFirstReading = true;
    private Handler uiHandler = new Handler(Looper.getMainLooper());

    public RandomItemFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentItemRandomBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (accelerometer == null) {
            binding.textViewInstruction.setText("抱歉，您的设备不支持摇一摇功能（缺少加速度传感器）。");
            binding.imageViewShakeIcon.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isFirstReading = true;
        if (accelerometer != null) {
            sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (accelerometer != null) {
            sensorManager.unregisterListener(this);
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            long currentTime = System.currentTimeMillis();
            // 忽略短时间内的连续触发
            if ((currentTime - lastShakeTimestamp) < SHAKE_SLOP_TIME_MS) {
                return;
            }

            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            if (isFirstReading) {
                lastX = x;
                lastY = y;
                lastZ = z;
                isFirstReading = false;
                return;
            }

            float deltaX = x - lastX;
            float deltaY = y - lastY;
            float deltaZ = z - lastZ;

            lastX = x;
            lastY = y;
            lastZ = z;

            // 计算加速度的模，转换为G力
            float gForce = (float)Math.sqrt(x*x + y*y + z*z) / SensorManager.GRAVITY_EARTH;

            // 阈值 SHAKE_THRESHOLD_GRAVITY 意味着设备受到的合力超过多少G
            // 当手机静止时，gForce 约等于 1G，当摇动时，这个值会瞬间增大
            if (gForce > SHAKE_THRESHOLD_GRAVITY) {
                lastShakeTimestamp = currentTime;
                uiHandler.post(this::openRandomTool);
            }
        }
    }

    private void openRandomTool() {
        List<ToolItem> allTools = ToolRepository.getBaseToolList();
        if (allTools == null || allTools.isEmpty()) {
            Toast.makeText(getContext(), "没有可用的工具列表", Toast.LENGTH_SHORT).show();
            return;
        }

        List<ToolItem> launchableTools = new ArrayList<>();
        for (ToolItem tool : allTools) {
            if (tool.getTargetActivityClass() != null) {
                launchableTools.add(tool);
            }
        }

        if (launchableTools.isEmpty()) {
            Toast.makeText(getContext(), "没有可随机打开的工具", Toast.LENGTH_SHORT).show();
            return;
        }

        Random random = new Random();
        int randomIndex = random.nextInt(launchableTools.size());
        ToolItem selectedTool = launchableTools.get(randomIndex);

        // 更新UI显示即将打开的工具
        binding.textViewOpenedTool.setText("即将打开：" + selectedTool.getName());
        binding.textViewOpenedTool.setVisibility(View.VISIBLE);

        // 短暂延迟后启动Activity
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (getContext() == null) return;

            Intent intent = new Intent(getActivity(), selectedTool.getTargetActivityClass());
            try {
                startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(getContext(), "无法打开工具：" + selectedTool.getName(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            // 恢复提示文本
            if (binding != null) {
                binding.textViewOpenedTool.setVisibility(View.GONE);
            }
        }, 1000);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // 传感器精度变化，暂时不处理
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}